<template>
<master title="单位用户管理">
  <listpage ref="listpage"></listpage>
</master>
</template>
<script type="text/javascript">
(function (G) {
  G.vue({
  "usingComponents": {
  	"master": "/components/Master/Master",
    "listpage": "/components/List/Table/Table",
    "mixinput": "/components/Input/Mixinput/Mixinput"
  }
},{
    data: {
      title: '',
      attr:{
        actions:[]
      },
      unitNickName:'',
      platform:G.platform,
      visible:false,
      uploadUsers:[],
      unitId:'',
      postNum:0,
      putNum:0,
      failNum:0
    },
    methods: {
      openUpload(){
        this.successNum = 0
        this.failNum = 0
        this.uploadUsers = []
        this.visible = true
      },
      beformUpload(file){
        let reader = new FileReader()
        reader.onload = ev => {
          let workBook = XLSX.read(ev.target.result, {type: 'binary', cellDates: true})
          let workSheet = workBook.Sheets[workBook.SheetNames[0]]
          const data = XLSX.utils.sheet_to_json(workSheet)
          this.uploadUsers = data
        }
        reader.readAsBinaryString(file)
      },
      save(){
        let promises = []
        let item = new G.Item()
        item._do()
        for(let i = 9; i < this.uploadUsers.length; i ++){
          item._push((next) => {
            let row = this.uploadUsers[i]
            let user = {
              unitId:this.unitId,
              userName:row.__EMPTY,
              name:row['填写须知：'] || row.__EMPTY_1,
              nickName:row.__EMPTY_1 || row['填写须知：'],
              dept:row.__EMPTY_3,
              sex:row.__EMPTY_4 == '男' ? 1 : 2,
              phone:row.__EMPTY_5,
              //是否启用
              status:row.__EMPTY_11 == '已激活' ? 1 : 0,
              //是否开启
              wxNotify:row.__EMPTY_13 == '已关注' ? 1 : 0,
              source:'wecom'
            }
            G.get('/api/model/user',{userName:user.userName}).then(res => {
              if(res.length){
                user.id = res[0].id
                G.put('/api/model/user',user).then(res => {
                  if(!res.errorMsg) {
                    this.putNum ++
                  }else{
                    this.failNum ++
                  }
                  next()
                })
              }else{
                G.post('/api/model/user',user).then(res => {
                  if(!res.errorMsg) {
                    this.postNum ++
                    G.post('/v1/wecom/send_msg',{
                      userIds:res.id,
                      text:{
                        content:`${res.nickName},欢迎入驻智慧环卫综合应用管理系统!`
                      }
                    })
                  }else{
                    this.failNum ++
                  }
                  next()
                })
              }
            })
          })
        }
        item._push(next => {
          //this.visible = false
        }) 
      },
      load: function (next) {
        this.selectComponent('#listpage').load(next);
      },
      refresh: function (next) {
        this.selectComponent('#listpage').refresh(next);
      },
      onPullDownRefresh: function (event) {
        this.refresh(function () {
          G.stopPullDownRefresh();
        })
      },
      onReachBottom: function (event) {
        this.load();
      },
      edit: function (event) {
        var unitNickName = this.getData('unitNickName');
        var modeleditquery = {
          values: event.detail,
          refresh: this.refresh,
          title:'修改' + event.detail.userName + ' ' + unitNickName,
          tips:'变更' + unitNickName + '可能导致数据异常，请谨慎操作!',
          models: {
            _id:{
              label:''
            },
            unitId:{
              label:'变更后' + unitNickName,
              attr:this.getData('attr'),
              type:'select'
            }
          },
          url: '/api/model/user',
          meth:'PUT',
          submit:function(data){
            return event.detail.unitId != data.unitId ? data : false
          }
        }
        G.Storage.set('modeleditquery', modeleditquery);
        this.$go('/pages/model/edit/edit');
      }
    },
    mounted: function (query) {
      var _this = this;
      var userNickName = G.Storage.get('nickNames').user || '用户';
      var unitNickName = G.Storage.get('nickNames').unit || '单位';
      this.unitId = query.unitId
      G.ajax('/api/model/unit',function(_ret){
        if (!_ret.errorMsg){
          _this.selectComponent('#listpage').init({
            getUrl: {
              url: '/api/model/user',
              data: {
                //userName:{$ne:'admin'},
                unitId: { $regex: query.unitId }
              }
            },
            models: {
              userName:{
                label:'用户名'
              },
              name:{
                label:'姓名'
              },
              nickName:{
                label:'昵称'
              },
              phone:{
                label:'手机号'
              },
              dept:{
                label:'企业微信部门'
              }
            },
            searchKey: 'name',
            canBack:true,
            canAdd:false,
            canCheck:false,
            actions: {
              edit: {
                action: function (event) {
                  _this.edit(event);
                },
                name:'变更'
              }
            }
          })
          _this.load();
          _this.setData({ unitNickName:unitNickName,attr: { actions: _ret }, unitId: query.unitId, title: query.name + ' ' + userNickName + '管理' });
          G.setNavigationBarTitle({
            title: query.name + ' ' + userNickName + '管理'
          })
        }
      },{
        data:{
          sql:'unitUser_unit'
        }
      })
    }
  });
})(Y)
</script>
<style scoped>
.list{
  margin:32rpx;
}
.itemDiv{
  padding:16rpx 0rpx;
}
.itemTitle{
  padding-bottom:16rpx;
}
.userNoData{
  text-align: center;
  line-height: 96rpx;
}
</style>